C Programming Language

A. Tips to Build Programming Logic / Skills

1. Learn Basic Fundamentals: Theory / Knowledge
2. Pen & Paper (best tools) & make self personal notes
3. Think with different angle and code
4. Dry run code
5. Be adventurous and explore as many questions as you can
6. Regularity (code Everyday)
7. Be Patience and Practice
8. Go from Basic / Fundamental (step by step)
9. DSA (concept of Data Structure & Algorithm)
10 Work for Projects

B. Technical Terms:

B. Programming Language: is the set of rules and codes that provides method (syntax) to instruct the computer to perform certain operations. E.g. C, C++, Pascal, Java, Python etc. It is used to create programs/ software depending upon tasks to be performed and the knowledge of the programmer.

C. Why Programming Languages?


i. To develop logics & capacity to express & implement ideas
ii. to improve knowledge for choosing appropriate languages
iii. To generate and develop the ability to learn and use new languages
iv. To build the logic of significance of implementation
v. Overall advancement of computing

D. Characteristics of Good Program

Portability: Program should compile & run smoothly on different platforms & supported by many different computer systems without failure.
Efficient:A program should take less space and time to execute & perform the required operation effectively.
Reliable:Program should be executable & workable smoothly in every version and perform in all simple to complex conditions.
cheaper:Cost of program must be measured over the quality, life of program and both cost & human cost of producing these programs.
Flexible:A high flexible software is always ready for a new world of possibilities to meet new requirement and allows to add new features without changing existing module.
MaintainabilityA program should be easy to read, understand & have quality to easily meet new requirements. It should also prevent unwanted works to reduce maintenance cost in future.
Documentation
Generality

E. Types / Generation of Programming Language

A. Low Level Languageis machine-dependent (0s & 1s) programming language processes by Processor directly without any language translators so, it can run very fast. Low-level language is further divided into two parts –
i. Machine Language / First Generation
ii. Assembly Language / Second Generation
B. High Level Language
iii. Procedural-Oriented Language / 3rd Gen.
iv. Problem-Oriented Language / 4th Gen.
v. Natural Language / 5th Gen.

1. Machine Languageis also called as machine code / object code / first Gen., normally displayed in binary or hexadecimal form (base 16) form. It does not require a translator to convert the programs because computers directly understand and process the instruction.
Advantages:
a. It is translator free, can be directly executed by system
b. It is faster in execution & efficiently utilizes memory because it is possible to keep track of each bit of data.
Disadvantages:
a. It is very difficult to understand and difficult and complex to develop program.
b. It is machine dependent, so as per the architecture specification, it is specified, costly & difficult.
c. Difficult to find the errors (bug), troubleshoot (debug) and modify the code.
d. Reduce programming efficiency as difficult to remember instructions, code and locations.


2. Assembly Language: It represents the set of instructions in a symbolic notation and human-understandable form to write programs. It uses an assembler to convert the assembly language to machine language. Assembly language instructions are represented as alphanumeric symbolic codes known as mnemonics.
Advantages:
- It requires less memory and less execution time to execute a program
- Relatively easy to understand and use
- Less error prone
- More control on hardware
- More efficient than high level language
Disadvantages:
- Machine dependent
- Difficult to learn
- Takes more time to develop
- Less efficient and slower than first generation
- No support for modern software engineering technology:
- No standardization

2. High Level Programming Language:

High Level Programming Language:is human understandable & user friendly but machine independent language.
The instructions in HLL, known as source program are transportable but non-executable, it requires a compiler or interpreter to translate the program into machine language.
HLL is easy to learn, write and maintain. E.g. Python, Java, JavaScript, C++, LISP etc.
Translator checks syntax, if syntax is correct, translates into equivalent machine codes called object programs. If syntax error it generates error messages.
Advantages:
- Easy and faster to program and debug
- Easy to learn and understand
- Readability than first & second gen..
- Lower development & maintenance cost
- Improve programmers' efficiency
Disadvantages:
- Power control on hardware
- Slower and less efficient in execution
- Requires translator
- Requires IDE (integrated development environment) for compilation and execution etc.

Types of High Level Programming Language:

1. Procedural-Oriented programming (POP) language: A programming paradigm that uses procedures or functions to abbreviate and categorize the code into reusable blocks is a procedural programming language. Eg. C, Pascal and FORTRAN. is used by a software programmer to create a program that can be accomplished by using a programming editor like IDE, Adobe Dreamweaver, or Microsoft Visual Studio etc.

Features:
- It is easy & faster to learn, understand, develop, debug and maintain the programs.
- Easily track the program flow and code can be reused in different parts of the program.
- Provides better documentation and portability.
- Standardized and machine independent.

Limitations:it requires translator program and executes slowly and procedural code is difficult to relate to real world objects.

2. Object-Oriented programming (OOP) language: is based upon the objects, where programs are divided into small parts called objects. It is used to implement real-world entities like inheritance, polymorphism, abstraction, etc. in the program to makes the program reusable, efficient, and easy-to-use. Eg. Java, Python, C++, Ruby etc.

Features:
- Use of standard math symbols and mathematical expression and operations.
- It requires less time, cost and effort to develop different types of software applications
- It required less number of instructions for performing a specific task.
- They possess a friendly interface.
- It allows the efficient use of data by implementing various database concepts.

Limitations:it requires translator program and executes slowly and procedural code is difficult to relate to real world objects.

3. Natural languages (5GL): (also known as Logic / Visual programming languages) are still in development stages. It based on formal logic, consists of a cluster of logical statements or rules that determine relationships among objects. A Natural language is typically used for communication and may be spoken, signed language (manual communication and body language) to convey meanings, hands, arm, facial expression, or written. Eg.: Mercury, Prolog (Programming with Logic), LISP (List processing), OPS5.

Features:
- It allows user to communicate with computer simply and easily, normally using English.
- Programs make much more interactive and interesting.
- Relieves the burden of learning syntax, no training.
- It can be used to query the database in a fast and efficient manner etc.

F. Language Translators/ Processors

Language Translators:, is a system software that translates source code from one programming language to another and also identify errors during translation. The process of converting a program written in a High-level or Assembly language into machine languages is known as Decoding or Translating.

There are three types of language processors: assembler, compiler, and interpreter.
Interpreter: translates & run single statement at a time into machine language.
Compiler: translates and run all instruction at one into machine language.
Assembler: a software that converts code of assembly language into machine language.

Compiler
- Compiler translates whole program into machine code at a time
- Compiler traps the errors before compiling the complete program
- Compiling and execute process is incredibly faster
- Intermediate object code is generated
- Difficult to debug
- Requires more memory
- E.g. C, C++, Java.

Interpreter
- Interpreter translates single statement of a program at a time
- Traps the errors before translating a line at a time
- Translation process is slower
- No intermediate object code is generated
- Easy to code and debug
- Requires less memory
- E.g. BASIC, Visual Basic

G. Programming Errors:

Programming Errors: means an error or defect that occurs during the development or encoding of a computer program, software, or application, which make abnormal behavior or incorrect operation of a computer system.
Programming errors are also known as the bugs or faults, and the process of removing these bugs is known as debugging.
These errors are detected either during the time of compilation, execution or and implementation.

Different common types of Programming Errors are:
1. Syntax error / Compilation errors
2. Logical error
3. Semantic error
4. Run-time error
5. Linker error
6. Interface errors
7. Resource errors etc.

1. Syntax errors:
Syntax errors occur when code violates the rules of the programming language such as missing semicolons, brackets, or wrong indentation of the code.
These errors are generally made by beginners and can be easily debugged or corrected.
Eg.: syntax errors:
Int a = 5
int 3 = b;
printf( a is greater than b);
Eg.: correct syntax
int a = 5;
int b = 3;
printf("%d is greater than %d",a,b);

2. Logical errors: Logical errors are the type of errors that occurs when incorrect logic is implemented in the code and the code produces unexpected output.
The occurrence of these errors mainly depends upon the logical thinking of the developer.
Eg.: Logical errors:
for(a=1; a>=10; a++)
Or
for(a=1; a<=10; a--)
Eg.: correct syntax
for(a=1; a<=10; a++) Or
for(a=1; a<=10; a++)

3. Semantic errors: Semantic errors are the errors that occurred when the statements are not understandable by the compiler or an user.
Due to semantic error (error in data statement), incorrect or unexpected output is produced.
Eg.: Semantic errors:
int a,b;
Avg=a+b/2;
printf("the average is %d",a);
Eg.: correct syntax
int a,b;
Avg=(a+b)/2;
printf("the average is %d",Avg);

4. Run-time errors: The errors exist during the execution-time even after the successful compilation known as run-time errors. These errors are very difficult to find, as the compiler does not point to these errors.
Eg.: Run-time errors:
int b=2/0;
printf("The value of b is : %d", b);
Eg.: correct syntax
int b=2;
printf("The value of b is : %d", b);

5. Linker errors: Linker errors are mainly generated when the executable file of the program is not created.
The most common linker error that occurs is that we use Main() instead of main().
Eg.: Run-time errors:
int Main() {
int a=78;
printf("The value of a is : %d", a);
Eg.: correct syntax
int main() {
int a=78;
printf("The value of a is : %d", a);
}

Program Solving Technique:

Method or Process to solve the Problems (Tasks):
- Problem understanding:
- Problem representation using any designing tools
- Program coding
- Program testing and debugging
- Implementation of Program

A. Program Design Tools:

Program design tools are methods used by programmer to develop the logical sequences for designing program or solve the problems.
When we go for SDLC (Software Development Life Cycle), we use many phases: Problem defining, System analysis, Feasibility study, System designing, coding, testing, implementing, maintenance etc.
During the Designing process we use designing tools for clear broad logic before coding.
Program designing tools are:
=> Algorithm,
=> Flowchart
=> Data Flow Diagram (DFD)
=> Entity Relational Diagram (ERD)
=> Context Diagram
=> Decision Tree
=> Decision Table etc.

B. Advantages of Effective Program Design Tools

Increase Efficiency: Tools can automate repetitive tasks, such as testing, debugging, deployment etc.
=> Increase Productivity:
=> Improve Collaboration:
=> Improve Code Quality:
=> Documentation
=> Improve Security
=> Collaboration and Teamwork
=> Code Reusability:
=> Faster development cycle
=> Debugging & Profiling
=> Learning & Skill development
=> Version control etc.

C. Program Tool: ALGORITHM

Algorithm is the set of sequential series of instruction (activities/ operations) to solve problem or perform tasks.
Properties / characteristics of an Algorithm: Major Guideline while writing ALGORITHM
=> Finiteness: it must have finite number of steps and end after finite time.
=> Input: it defines/determines the input, requirements for the program
=> Output: it must provide desired output(s)/ result(s).
=> Processes: it contains processing, manipulation, logical operations using identifiers (variables, functions etc.).
=> Well-defined & Precise: each step must be clear, well-defined & precise
=> Effectiveness: Each step must be simple, clear and executable and take finite time to operate.
=> Programming language independent:

D. Advantages of C Language

Advantages of C Language
Fast and efficient
Easy for debugging, testing & maintaining
Simple, versatile & portable general purpose language
Having high degree of language mobility
No limitation in programming
Structured language with functional flow control construct
User friendly
Having 32 keywords easy to remember
Having ability to extend itself and create more library function

E. Disadvantages of C languages:

Disadvantages of C languages:
a. No running time checking
b. It is case sensitive
c. No any concept of constructor and destructor
d. No concept of data hiding, inheritance and polymorphism
e. No enough library function to handle current programming environment
f. Mostly focus on structures and procedures not to data of real world situation
g. May compile time overhead due to misplacing and excessive use of pointer

F. Programming Structure of C program

Syntax:

Documentation section
Link section
Definition section
Global declaration section
The main () function section
{ Declaration section
Executable section };
Sub program section
Function 1
{ statement 1 }
Function n
{statement n}

Example:

/*remarks */
#include <stdio.h>
#include <conio.h>
void main()
{ int a, b;
printf(“Enter the value of a & b\n”) ;
scanf (“%d%d, &a,&b);
printf (“the value of a=%d\n”,a) ;
printf (“the value of b=%d\n”,b) ; getch(); }

G. Compiling Process:

Compiling Process:Compiler is the program used to transform program written in high level programming language from source code into object code and pass through the linker.
Linker combines modules and gives real values to all symbolic address.

a. Documentation section consists set of comments which is optional part.
b. Link section
provides instruction to compiler to link functions. It includes header files which contain the definition of different library functions.
c. Definitions section
defines all the symbolic constants which are defined at the beginning before main() function. It is also optional part.
d. Global declaration
where we declare variable which are used inside, outside in many functions.
e. main() function contains 2 parts:
declaration and executable parts. Declaration part declares all variables used in executable part. Executable part contains at least one statement and enclosed by pair of braces {}.
f. Sub-program section:
contains all the user defined functions that are called in main function.

Tokens in C:

• Token is a smallest part of C programming language which is used to write statement.
• In any programming language, a program is made up of smallest individual syntactic elements. The basic and smallest element used to develop the program and recognized by the compiler is called as C Tokens.

Keywords:

• Keywords: the reserved words that have predefined meaning and standard in C language. They serve as building blocks for program statements & must be written in lowercase. They cannot be used as identifiers or variable.
• The ANSI defines 32 keywords based on ASCII.
The following are reserved words in C which not be used as constant or variable or any other identifier names.

Identifiers:

Identifiers: C identifier is a name used to identify a variable, structure, function, or any other user-defined item. It starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, & digits.
Rules to declare or define identifiers:
• C does not allow punctuation characters such as @, $, and % within identifiers. C is a case sensitive programming language.
• Start with only alphabet or underscore
• Does not enclosed by single or double quote
• No symbols and keywords are used except underscore.
• No blank space is used in between.
• It allows both upper case and lowercase character as separate identifier.

Data Types in C:

• C language provides us the way to hold any type of data for programming which is called data type. The data might be in the form of number, character, string, or record.
• Data type is an instruction that is used to declare the category of type of variable being used in the program. Any variable in program must be declared before using it. It determines the way a computer organizes data in memory.
• In C programming, data types are declarations for variables. This determines the type and size of data associated with variables.
• Data types in the c programming language are used to specify what kind of value can be stored in a variable. These are categorized into two categories. They are:

Variable:

Variable:Those entities which hold either numeric or alphanumeric values in a program and may change its value throughout the time of program execution are known as variables. It is the character set used store value temporarily.

Rule for writing variable:
• Variable names start with alphabet or underscore sign only, it doesn't start with any number.
• Variable names should not have blank space in between. Eg, first name is invalid, firstname is valid
• Keywords cannot be used as variable name. Eg, printf = 2; is invalid, num = 2; is valid
• Uppercase variable names are different from lowercase variable names. Eg, age = 2 is different from AGE = 2
• Examples int a, sum, percentage, age etc.

[Note: try to use relevant word as variable name without using any special symbol]

Constants: Numeric constant & String constant:

Contant:Constant value is the one which does not change during the execution of a program. Constant value are known or fixed value which can be stored at a location in the memory. C supports several types of constants as its data type:

Integer constant:
is a sequence of exact digits without decimal value. Rules to write integer constant are:
It must have a digit but without decimal point
It may contain either + or – sign
It should not contain comma and space in between. (1,000 is invalid.)

C allows three types of integers:
i. Decimal integer : 100 0 -50 +40
ii. Octal integer: O O5 O67
iii. Hexadecimal integer: OX OX5 OX9E

Float constant: can be written either in decimal, without decimal or an exponent form (or both). Writing rules same as integer constant but / sign cannot be used.

Character constant:is a single character, enclosed in apostrophes (single quotation mark) e.g. ‘a’ ‘A’ ‘3’

String constant: is a set of characters enclosed in double quotation marks. E.g. “Nepal” “1234” “God bless you” “ .”

Symbolic constant: is a type of constant that substitutes the value or express to constant name. it is defined by using the pre-processor #define.

Operators:

Operators:Operators are the special symbol or sign used to instruct for calculation or perform some specific function or operation on operands or values.

Types of operators:
a) Arithmetic operator: + , - , * , / , %
b) Relational operator: > , < ,>= , <= , !=(not equal to) ,==(equal to) [Note: Here in C language if you want to compare the equal to is referred by==(two equals)]
c) Assignment operator:=is an assignment operator. [Note If a=2 then it means 2 is assigned to variable a, it does not mean a also has value 2 and both are equal.]
d) Logical operator
   For logical AND use &&
   For logical OR use ||
   For logical NOT use !

Data Types in C:

B. Exercise

Data Types in C:

B. Exercise

Data Types in C:

B. Exercise

Data Types in C:

B. Exercise

A. Summary

B. Practice Questions

C. Lab Practive

//1. to enter name, roll_no. and marks of 10 students and store them in the file :
#include (stdio.h)
main()
{ FILE *f; //file pointer
char name[10];
int roll_no,L;
float marks;
f=fopen("record.txt","w"); //creating file in write mode
for(L=1;L <=10;L++)
{ printf("Enter roll no");
scanf("%d",&roll_no);
printf("Enter name");
scanf("%s",&name);
printf("Enter marks");
scanf("%f",&marks);
fprintf(f,"%d \t %s\t %f\n",roll_no,name,marks); //write data into file; }
fclose(f); //closing
file; }

//2. to store roll, name, age, gender into "info.txt" fiLe:
#include stdio.h>
#include string.h>
#include conio.h>
main(){
FILE *fp;
int roll, age, p, n;
char name[10], sex[10], ch='Y';
fp = fopen ("info.txt","a");
while (ch == 'Y' || ch == 'y')
{ printf ("Enter roll");
scanf ("%d", &roll);
printf ("Enter Name");
scanf ("%s", &name);
printf ("Enter Age");
scanf ("%d", &age);
printf ("Enter Gender");
scanf ("%s", &sex);
fprintf (fp,"%d\t %s\t %d\t %s\n", roll, name, age, sex);
printf ("Press Y for nest record");
ch = getche ();
}
fclose (fp);
}

//3. to display contents: roll,name,age,sex from "infoitxt" fiLe:
#include (stdio.h>
main(){
FILE *fp;
int roll,age,p,n;
char name[10],sex[10];
fp=fopen("info.txt","r"); while((fscanf(fp,"%d\t %s\t %d\t %s\n",&roll,name,&age,sex))!=EOF)
{
printf("Roll:%d\t Name: %s\t Age: %d\t %s\n",roll,name,age,sex);
}
fclose(fp);
}
//this program reads contents as defined format of data type and displays accordingly till the end of content in the file:

//4. to dispLoy contents from "infoitxt" fiLe:
#include (stdio.h>
main(){
FILE *fp;
char ch;
fp=fopen("info.txt","r");
while((ch=getc(fp))!=EOF)
{
putchar(ch);
}
fclose(fp);
}
//this program reads as all characterwise and displays accordingly till the end of content in the file:

/*5. to take a number and check whether it is positive, negative or zero using user-defined function.*/
#include (stdio.h>
char check (int);//declaration of function
main()
{ int n;
printf ("Enter a number");
scanf ("%d", &n);
check(n); } //calling function
char check (int n) // definition part of function
{
if (n>0){
printf ("The number %d is Positive",n);
}
else if (n<0){
printf("The number %d is Negative",n); }
else{ printf("The number %d is Zero",n); } }

/*6. a program to add record on file "Record.dat" under the fields: ID, Name, Post and Salary of nth employees.*/
#include (stdio.h>
#include (conio.h>
main(){
FILE *fp;
int ID, sal;
char name[10], post[10], ch='Y';
fp = fopen ("Record.dat","a"); //append mode is to add records
while (ch == 'Y' || ch == 'y')
{ printf ("Enter ID");
scanf ("%d", &ID);
printf ("Enter Name");
scanf ("%s", &name);
printf ("Enter Post");
scanf ("%s", &post);
printf ("Enter Gender");
scanf ("%d", &sal);
fprintf (fp,"%d\t %s\t %s\t %d\n", ID, name, post, sal);
printf("Press Y for nest record");
ch = getche (); }
fclose (fp); }

/*7. program to take ID, Name, Post and Salary of nth employees and print the record of 5 higher salary receivers.*/
#include (stdio.h>
struct emplyees{
int ID;
char Name[10],Post[10];
float sal;
}e[100],holder;
main(){
int n, p, p1;
printf("Enter the number of employees");
scanf("%d",&n);
for(p=0; p < n; p++){
printf("Enter ID");
scanf("%d", &e[p].ID);
printf("Enter Name");
scanf("%s", &e[p].Name);
printf("Enter Post");
scanf("%s", &e[p].Post);
printf("Enter Salary");
scanf("%f", &e[p].sal); }
for(p=0; p < n; p++)
{ for(p1=0; p1 < n; p1++) {
if(e[p].sal>e[p1].sal)
{holder=e[p];
e[p]=e[p1];
e[p1]=holder;
}
}
}
printf("The 5 higher salary receivers:\n");
for(p=0;p <5;p++){
printf("ID: %d\n Name: %s\n",e[p].ID,e[p].Name);
printf(" Post:%s\n Salry: %.2f\n",e[p].Post,e[p].sal); }
}

/* program to take roll, name, age of nth numbers of students and print by name alphabetically.*/
#include (stdio.h>
#include (string.h>
struct students{
int roll,age;
char Name[10];
}e[100],holder;
main(){
int n, p, p1;
printf("Enter the number of students");
scanf("%d",&n);
for(p=0;p < n; p++){
printf("Enter Roll No.");
scanf("%d",&e[p].roll);
printf("Enter Name");
scanf("%s",&e[p].Name);
printf("Enter Age");
scanf("%d",&e[p].age); }
for(p=0; p < n; p++)
{ for(p1=0; p1 < n; p1++)
{ if((strcmp(e[p].Name,e[p1].Name))<0)
{ holder=e[p];
e[p]=e[p1];
e[p1]=holder; } } }
printf("The list in alphabetical order:\n");
for(p=0; p < n; p++){
printf("Roll: %d\n Name: %s\n",e[p].roll,e[p].Name);
printf(" Age:%d\n",e[p].age); }
}